#include <algorithm>
#include <vector>

using namespace std;
class Solution {
public:
  vector<vector<int>> merge(vector<vector<int>> &intervals) {
    sort(
        intervals.begin(), intervals.end(),
        [](const vector<int> &a, const vector<int> &b) { return a[0] < b[0]; });

    vector<vector<int>> ans;
    vector<int> tmp;

    for (auto &elem : intervals) {
      if (ans.empty() || elem[0] > tmp[1]) {
        if (!tmp.empty()) {
          ans.push_back(tmp);
        }
        tmp = elem;
      } else {
        if (elem[1] > tmp[1]) {
          tmp[1] = elem[1];
          continue;
        }
      }
    }
    if (!tmp.empty()) {
      ans.push_back(tmp);
    }
    return ans;
  }
};

int main() {
  Solution s;
  vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
  s.merge(intervals);
}